package com.ming.sportdemo.filter;

import com.ming.sportdemo.Exception.RoleException;
import com.ming.sportdemo.annotation.NeedFinalRole;
import com.ming.sportdemo.annotation.NeedRole;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.net.URLDecoder;

public class RoleAuthentication implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //访问方法才拦截！
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String role = URLDecoder.decode(request.getHeader("role"),"UTF-8");
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(NeedRole.class)){
            if(role.equals("管理员")||role.equals("超级管理员")){
                return true;
            }else {
                throw new RoleException("角色权限异常");
            }
        }
        if (method.isAnnotationPresent(NeedFinalRole.class)){
            if(role.equals("超级管理员")){
                return true;
            }else {
                throw new RoleException("角色权限异常");
            }
        }
        return true;
    }
}
